import UserService from '@/api/user';
import { setCurrentStep } from '@/views/register/util';
import { createRouter, createWebHistory, isNavigationFailure } from 'vue-router';
import { Storage } from '@/utils/Storage';
export const routes = [
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/home.vue'),
        meta: {
          title: '首页',
        },
      },
      {
        path: '/about',
        name: 'About',
        component: () => import('@/views/about.vue'),
        meta: {
          title: '关于我们',
        },
      },
      {
        path: '/search-position',
        name: 'SearchPosition',
        component: () => import('@/views/search-position.vue'),
        meta: {
          title: '查询职位',
        },
      },
      {
        path: '/position/:positionId',
        name: 'PositionDetail',
        component: () => import('@/views/position.id.vue'),
        meta: {
          title: '职位详情',
        },
      },
      {
        path: '/company-list',
        name: 'CompanyList',
        component: () => import('@/views/company-list.vue'),
        meta: {
          title: '企业列表',
        },
      },
      {
        path: '/company/:id',
        name: 'CompanyDetail',
        component: () => import('@/views/company.id.vue'),
        meta: {
          title: '企业详情',
        },
      },
      {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/register/index.vue'),
        meta: {
          title: '注册',
        },
      },
      {
        path: '/resume/:resumeId?',
        name: 'ResumeDetail',
        component: () => import('@/views/resume/index.vue'),
        meta: {
          title: '简历详情',
        },
      },
      {
        path: "/job-ai",
        name: "JobAi",
        component: () => import('@/views/job-ai.vue'),
        meta: {
          title:"职业AI"
        }
      }
    ],
  },
  {
    path: '/:catchAll(.*)*',
    name: 'NotFound',
    component: () => import('@/views/not-found.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(_to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    }
    return { top: 0 };
  },  
});

router.beforeEach(async (to, from, next) => {
  const defaultRoutePath = '/';
  const APP_WHITE_LIST = ['Home', 'About', 'SearchPosition', 'PositionDetail', 'CompanyList', 'CompanyDetail', 'JobAi'];

  const userStore = useUserStore();
  const token = userStore.token;
  const callback = () => {
    if (to.name === 'Home') {
      next({ path: defaultRoutePath });
    } else {
      const hasRoute = router.hasRoute(to.name!);
      if (!hasRoute) {
        next({ name: 'NotFound' });
      } else {
        next();
      }
    }
  };

  const registerCallback = (index: number) => {
    setCurrentStep(index);
    if (to.path === '/register') next();
    else next({ path: '/register', replace: true });
  };

  try {
    if (token) {
      if (!userStore.hasUserInfo) {
        // 没有用户信息
        const resp = await UserService.selectSeekerImprove<any>();
        if (resp.code === 200) {
          const data = resp.data;
          userStore.setUserInfo(data);
          // 根据返回的信息，跳转到不同的注册步骤
          // 1. 是否有求职意向，如果没有则进入注册 步骤1 (索引为0，索引递增)
          // 2. 没有真实姓名，则进入注册 步骤2
          // 3. 判断教育经历是否存在，不存在则进入 步骤3
          // 4. 判断工作经历是否存在，不存在则进入 步骤4 （这个步骤可以跳过）
          const Register_0 = Storage.get('Register_0');
          const Register_1 = Storage.get('Register_1');
          const Register_2 = Storage.get('Register_2');
          if (Register_0 || Register_1 || Register_2) {
            if (Register_0) {
              registerCallback(0);
            } else if (Register_1) {
              registerCallback(1);
            } else if (Register_2) {
              registerCallback(2);
            }
          } else {
            if (!data?.seekerPurposeBo) {
              registerCallback(0);
            } else if (!data?.seekerBO?.name) {
              registerCallback(1);
            } else if (!data?.educationExperienceBo) {
              registerCallback(2);
            } else {
              if (to.path === '/register') {
                next('/');
              } else {
                next();
              }
            }
          }
        } else {
          // 没有用户信息，跳转到登录
          next({
            path: '/',
            // query: { redirect: to.name === 'Register' ? '/' : to.fullPath },
            replace: true,
          });
        }
      } else {
        // 有用户信息，但是去的时候注册页
        if (to.name === 'Register') next({ path: '/', replace: true });
        else callback();
      }
    } else {
      if (APP_WHITE_LIST.includes(to.name as string)) {
        // 在免登录名单，直接进入
        next();
        return;
      }
      next({
        path: '/',
        replace: true,
      });
    }
  } catch (error) {
    console.log(error)
    if (to.name === 'NotFound') {
      next();
    } else {
      next({ name: 'NotFound' });
    }
  }
});
router.afterEach((to, from, failure) => {
  if (to?.meta?.title) {
    document.title = `${to.meta.title} - 职虎`;
  }
  if (isNavigationFailure(failure)) {
    console.log('failed navigation', failure);
  }
});
export default router;
